package com.smart.six.encryption;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * DES加密
 *
 * @author junrui.wang
 * @create 2018/7/10
 */
public class DESUtils {
    private static Key key;
    private static String KEY_STR = "male";

    //指定DES加密解密的密钥
    static {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
            keyGenerator.init(new SecureRandom(KEY_STR.getBytes()));
            key = keyGenerator.generateKey();
            keyGenerator = null;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    //对字符串进行DES加密，返回BASE64编码加密的字符串
    public static String getEncryptString(String context){
        BASE64Encoder base64Encoder = new BASE64Encoder();
        try {
            byte[] contextBytes = context.getBytes("UTF8");
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptStrBytes = cipher.doFinal(contextBytes);
            return base64Encoder.encode(encryptStrBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //对BASE64编码的加密字符串进行解密，返回解密后的字符串
    public static String getDecryptString(String context){
        BASE64Decoder base64Decoder = new BASE64Decoder();
        try {
            byte[] contextBytes = base64Decoder.decodeBuffer(context);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] decoderStrBytes = cipher.doFinal(contextBytes);
            return new String(decoderStrBytes, "UTF8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String[] keys = {
                "root", "123456"
        };
        System.out.println("key | AESEncode | AESDecode");
        for (String key : keys) {
            System.out.print(key + " | ");
            String encryptString = getEncryptString(key);
            System.out.print(encryptString + " | ");
            String decryptString = getDecryptString(encryptString);
            System.out.println(decryptString);
        }
    }
}
